﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FlashCards.Model;

namespace FlashCards.WebApp.Security
{
    public class GroupsSecurityProvider
    {
        public static bool CanUserEditSets(string userName, int? groupId)
        {
            var acceptableRoles = new List<string> { "Owner", "Moderator", "NormalUser" };

            return IsRoleInList(userName, groupId, acceptableRoles);
        }

        public static bool CanUserAddUsers(string userName, int? groupId)
        {
            var acceptableRoles = new List<string> { "Owner", "Moderator" };

            return IsRoleInList(userName, groupId, acceptableRoles);
        }

        public static bool CanUserSetRoles(string userName, int? groupId)
        {
            var acceptableRoles = new List<string> { "Owner" };

            return IsRoleInList(userName, groupId, acceptableRoles);
        }

        static bool IsRoleInList(string userName, int? groupId, List<string> acceptableRoles)
        {
            if (!string.IsNullOrEmpty(userName) && groupId.HasValue)
            {
                using (var context = new FlashCardsEntities())
                {
                    var user = context.Users.FirstOrDefault(x => x.Nick == userName);

                    var groupRoleName = context.GroupMembers
                        .FirstOrDefault(x => x.UserId == user.UserId && x.GroupId == groupId)
                        .GroupRole.Name;

                    return acceptableRoles.Contains(groupRoleName);
                }
            }
            return false;
        }
    }
}